package com.heima.user.controller.v1;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.user.dtos.LoginDto;
import com.heima.user.service.ApUserService;
import com.heima.user.utils.SendSms;
import com.heima.user.utils.ValidateCodeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/v1/login")
@Api(value = "app端用户登录-控制器")
public class ApUserController {

    @Autowired
    private ApUserService apUserService;

    /**
     * 登录校验
     *
     * @return
     */
    @PostMapping("/login_auth")
    @ApiOperation("用户登录")
    public ResponseResult login(@RequestBody LoginDto dto) {
        ResponseResult result = apUserService.login(dto);
        return result;
    }

    /**
     * 获取验证码
     *
     * @param phone
     * @return
     */
    @PostMapping("/sendMsg")
    public ResponseResult generatCode(@RequestBody Long phone, HttpSession session) {
        if (StringUtils.isNotEmpty(phone.toString())) {
            //生成随机的4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            //调用阿里云提供的短信服务API完成发送短信
            SendSms.sendMsg(phone.toString(), code);

            //需要将生成的验证码保存到Session
            //session.setAttribute("phone",phone);
            //session.setAttribute(phone,code);
            //需要将生成的验证码保存到Redis,设置过期时间
            //redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return ResponseResult.okResult(code);
        }
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        return ResponseResult.okResult(code);
    }
}
